//
//  BLMusicView.m
//  百思不得姐
//
//  Created by hbl on 16/3/26.
//  Copyright © 2016年 hbl. All rights reserved.
//

#import "BLMusicView.h"
#import <YYAnimatedImageView.h>
#import "M13ProgressViewRing.h"
#import "BLBigImageViewController.h"
#import <YYWebImage.h>
#import <AVFoundation/AVFoundation.h>
#import "SVProgressHUD.h"
@interface BLMusicView()<AVAudioPlayerDelegate>
@property (weak, nonatomic) IBOutlet YYAnimatedImageView *pictureView;

@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UILabel *playCount;
@property (weak, nonatomic) IBOutlet M13ProgressViewRing *progressView;
@property (weak, nonatomic) IBOutlet UIButton *playButton;

@property (nonatomic, strong)AVAudioPlayer *player;

@property (nonatomic, assign)BOOL isPlaying;

@property (nonatomic, strong)UIButton *current;
@end

@implementation BLMusicView


- (IBAction)playMusic:(id)sender {
    UIButton *btn = sender;
    self.current = btn;
    if (!btn.selected) {
        btn.selected = YES;
        self.topic.isPlaying = YES;
          [SVProgressHUD show];
        dispatch_queue_t q = dispatch_queue_create("hbl", DISPATCH_QUEUE_SERIAL);
       
        dispatch_async(q, ^{
          
            if (self.player) {
                [self.player stop];
                self.player = nil;
            }
            NSData *musicData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:self.topic.voiceuri]];
            [[NSOperationQueue mainQueue]addOperationWithBlock:^{
               [SVProgressHUD dismiss]; 
            }];
            AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithData:musicData error:nil];
            self.player = player;
            player.delegate = self;
           
            [player prepareToPlay];
            [player play];
            
        });
    }else{
        [self.player stop];
        self.player = nil;
        btn.selected = NO;
        self.topic.isPlaying = NO;
    }
}

- (void)awakeFromNib
{
    self.autoresizingMask = UIViewAutoresizingNone;
    self.progressView.secondaryColor = [UIColor whiteColor];
    self.progressView.primaryColor = [UIColor whiteColor];
    self.progressView.hidden = YES;
    [self.pictureView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onClickPicture:)]];
    
    
}

- (void)onClickPicture:(UITapGestureRecognizer *)tap
{
    BLBigImageViewController *bigImage = [[BLBigImageViewController alloc]init];
    bigImage.topic = self.topic;
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:bigImage animated:YES completion:nil];
}


+ (instancetype)musicView
{
    return [[[NSBundle mainBundle] loadNibNamed:@"BLMusicView" owner:nil options:nil] lastObject];
}

- (void)setTopic:(BLTopic *)topic
{
    _topic = topic;
    self.playButton.selected = self.topic.isPlaying;
    [self.progressView setProgress:0.0 animated:NO];
    [self.pictureView yy_setImageWithURL:[NSURL URLWithString:topic.image2] placeholder:nil options:YYWebImageOptionSetImageWithFadeAnimation progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        self.progressView.hidden = NO;
        CGFloat progress = ((CGFloat)receivedSize)/((CGFloat)expectedSize);
        [self.progressView setProgress:1.0 * progress animated:YES];
    } transform:nil completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
        [self.progressView setProgress:1.0 animated:YES];
        self.progressView.hidden = YES;
    }];
    
    long min = topic.voicetime/60;
    long second = topic.voicetime%60;
    self.timeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld",min,second];
    
    self.playCount.text = [NSString stringWithFormat:@"播放%ld次",topic.playcount];
    
    if (topic.picLong) {
        
        self.pictureView.contentMode = UIViewContentModeScaleAspectFill;
        self.pictureView.clipsToBounds = YES;
    }else{
        
        self.pictureView.contentMode = UIViewContentModeScaleToFill;
    }
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [self playMusic:self.current];
}

@end
